package nl.vu.few.ibivu.biomodels.client.ui;

import java.util.ArrayList;
import java.util.Arrays;

import nl.vu.few.ibivu.biomodels.client.place.ModelPlace;
import nl.vu.few.ibivu.biomodels.client.ui.view.ModelBrowsingView;

import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.user.client.ui.Image;
import com.google.inject.Inject;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.AutoFitWidthApproach;
import com.smartgwt.client.types.FetchMode;
import com.smartgwt.client.types.RecordComponentPoolingMode;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.types.SortDirection;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.HTMLFlow;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.DataArrivedEvent;
import com.smartgwt.client.widgets.grid.events.DataArrivedHandler;
import com.smartgwt.client.widgets.layout.HLayout;

public class ModelBrowsingViewImpl extends ListGrid implements ModelBrowsingView {
	private Presenter presenter;
	private ListGridField editField;
	
	@Inject
	public ModelBrowsingViewImpl() {
		this.setStyleName("modelList");
		this.setBaseStyle("modelList");
		this.setHeaderBaseStyle("modelListHeaderButton");
		this.setWidth100();
		this.setHeight100();
		this.setCanResizeFields(false);
		this.setCanSort(true);
		this.setCanMultiSort(false);
		this.setCanRemoveRecords(true);
		this.setSelectionType(SelectionStyle.NONE);
		this.setCanPickFields(false);
		this.setCanReorderFields(false);
		this.setAlternateRecordStyles(true);
		this.setCanGroupBy(false);
		this.setShowHeaderContextMenu(false);
		this.setAutoFetchData(false);
		this.setDataFetchMode(FetchMode.PAGED);
		this.setShowAllRecords(false);
		this.setShowRecordComponents(true);
		this.setShowRecordComponentsByCell(true);
		this.setRecordComponentPoolingMode(RecordComponentPoolingMode.DATA);
		this.setCanExpandRecords(true);
        this.setShowEmptyMessage(true);
        this.setEmptyMessage("<br>You haven't saved any model yet.");
        
        this.setAutoFitWidthApproach(AutoFitWidthApproach.BOTH);
        this.setAutoFitFieldWidths(true);
        this.setAutoFitExpandField("name");
        this.setAutoFitClipFields("name");
        
        this.addDataArrivedHandler(new DataArrivedHandler() {

			@Override
			public void onDataArrived(DataArrivedEvent event) {
				ArrayList<ListGridField> gridFields = new ArrayList<ListGridField>(Arrays.asList(getFields()));
		        gridFields.add(gridFields.size() - 1, editField);
		        gridFields.get(1).setBaseStyle("modelListNameField");
		        setFields(gridFields.toArray(new ListGridField[gridFields.size()]));
			}
        	
        });
        
        editField = new ListGridField("edit", " ");
        editField.setAlign(Alignment.CENTER);
        editField.setAutoFitWidth(false);
        editField.setWidth(24);
        editField.setCanGroupBy(false);
        editField.setCanSort(false);
	}
	
	@Override
	protected Canvas getExpansionComponent(ListGridRecord record) {
		final HLayout canvas = new HLayout();
		canvas.setLayoutTopMargin(5);
		canvas.setStyleName("modelListExpandCanvas");
		canvas.setWidth100();
		canvas.setAutoHeight();
		String thumbnailSrc = record.getAttributeAsString("thumbnail");
		thumbnailSrc = (thumbnailSrc == null) ? "default.png" : thumbnailSrc;
		Image thumbnail = new Image(thumbnailSrc);
		thumbnail.setStylePrimaryName("modelListThumbnail");
		canvas.addMember(thumbnail);
		thumbnail.addLoadHandler(new LoadHandler(){

			@Override
			public void onLoad(LoadEvent event) {
				canvas.adjustForContent(false);
			}});
		
		String description = record.getAttributeAsString("description");
		if (description == null) {
			description = "<i>No description available.</i>";
		}
		HTMLFlow flow = new HTMLFlow();
		flow.setContents("<span class=\"modelListDescriptionHeader\">Description</span><div class=\"modelListDescriptionField\">"+
				description+"</div>");
		canvas.addMember(flow);
        return canvas;
	}

	@Override
	protected Canvas createRecordComponent(final ListGridRecord record, Integer colNum) {
		String fieldName = this.getFieldName(colNum);
		if (fieldName.equals("edit")) {
			ImgButton button = new ImgButton();
			button.setShowDown(false);
			button.setShowRollOver(false);
            button.setHeight(16);
            button.setWidth(16);
            button.setSrc("[SKIN]actions/edit.png");
            button.addClickHandler(new ClickHandler() {  
                public void onClick(ClickEvent event) {
                	// FIXME prevent the cast to long from int
                    presenter.goTo(new ModelPlace(Long.valueOf((long)record.getAttributeAsInt("id"))));
                }  
            });
            //button.setLayoutAlign(VerticalAlignment.TOP);
            return button;
		}
		else {
			return null;
		}
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
		this.setDataSource(presenter.getDataSource());
		this.sort("modifiedTime", SortDirection.DESCENDING);
        this.fetchData();
	}
	
}
